package com.itheima.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;

import com.itheima.service.CheckGroupService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Autowired
    private CheckItemDao checkItemDao;


    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = findAll(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(CheckGroup checkGroup,Integer[] ids) {
        if (checkGroupDao.add(checkGroup)) {
            setCheckGroupAndCheckItem(checkGroup.getId(),ids);
        }else{
            throw new RuntimeException("添加失败"+checkGroup.getName());
        }

    }

    @Override
    public void setCheckGroupAndCheckItem(Integer gid, Integer[] ids){
        if(gid==null||ids==null||ids.length==0||!checkGroupDao.setCheckGroupAndCheckItem(gid,ids)){
            throw new RuntimeException("添加失败");
        }
    }
    @Override
    public void deleteCheckGroupAndCheckItem(Integer gid){
        checkGroupDao.deleteCheckGroupAndCheckItem(gid);
    }

    @Override
    public Map<String,Object> findById(Integer id) {
        try {
            CheckGroup checkGroup = checkGroupDao.findById(id);
            Map<String,Object> map = new HashMap<>();
            List<Integer> list = new ArrayList<>();
            checkGroup.getCheckItems().forEach(checkItem -> {
                list.add(checkItem.getId());
            });
            checkGroup.setCheckItems(null);    //将检查项清除
            map.put("formData",checkGroup);
            map.put("tableData",checkItemDao.findAll(null));
            map.put("checkitemIds",list);
            return map;
        } catch (Exception e) {
            throw new RuntimeException("查询失败");
        }
    }

    @Override
    public Page<CheckGroup> findAll(String queryString) {
        return checkGroupDao.findAll(queryString);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        deleteCheckGroupAndCheckItem(checkGroup.getId());

        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

        checkGroupDao.edit(checkGroup);
    }

    @Override
    public void delete(Integer id) {
        deleteCheckGroupAndCheckItem(id);
        checkGroupDao.deleteById(id);
    }
}
